package band.wukong.practice.javase.core.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by IntelliJ IDEA.
 * User: Johnson
 * Date: 2012-8-25 9:35:36
 * To change this template use File | Settings | File Templates.
 */
public class TestURLConnection {
    public static void main(String[] args) throws Exception {

        // step 1. Create a URL
        URL url = new URL("http://www.baidu.com");
        URLConnection con = url.openConnection();

        // step 2. Connect to the server
        con.connect();

        // print header fields
        int n = 1;
        String key;
        while ((key = con.getHeaderFieldKey(n)) != null) {
            String value = con.getHeaderField(n);
            System.out.println(key + " = " + value);
            n++;
        }

        // print convenience functions
        System.out.println();
        System.out.println("getContentType: " + con.getContentType());
        System.out.println("getContentLength: " + con.getContentLength());

        System.out.println("getContentEncoding: "
                + con.getContentEncoding());
        System.out.println("getDate: " + con.getDate());
        System.out.println("getExpiration: " + con.getExpiration());
        System.out.println("getLastModifed: " + con.getLastModified());
        System.out.println();

        // step 3 and 4. Get an InputStream and encapsulate it
        BufferedReader in = new BufferedReader(new InputStreamReader(con
                .getInputStream()));

        // print first ten lines of contents
        String line;
        n = 1;

        // step 5. Read info from the stream
        while ((line = in.readLine()) != null && n <= 100) {
            System.out.println(line);
            n++;
        }

        if (line != null)
            System.out.println(". . .");

    }
}
